//http://192.168.2.123:8080/video
#include "v4a_hal.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include "bmp_encoder.h"
#include "USER_CFG.h"
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include "fileupdate.h"
#include "spi.h"
#include <net/if.h>        		  //for struct ifreq
#include <net/if_arp.h>
#include <arpa/inet.h>

#define ETH_NAME        "eth0"

#define IOCTL_LCD_BRIGHTNESS	_IOW('v', 27, unsigned int)	//brightness control
#define VIDEO_DISPLAY_ON	_IOW('v', 24, unsigned int)	//display on
#define VIDEO_DISPLAY_OFF	_IOW('v', 25, unsigned int)
#define FB_DEV "/dev/fb0"

#define PROCBUFSIZ                  1024
#define _PATH_PROC_NET_DEV        "/proc/net/dev"

extern int date_config_flag;
extern int time_config_en;
extern int date_config_en;
extern int real_offset;
extern int time_offset;
extern int date_offset;
extern int date_change;
extern int time_change;
extern int cur_bit;

char userbkgnd_bmp[4*1366*768] __attribute__ ((aligned(4)));
char userbkgnd_bmp_data[1366*768*4] __attribute__ ((aligned(4)));
unsigned int display_tmp_addr = 100;
extern IMGNODE bkgnd_fbcopy;
extern IMGNODE bkgnd_fbdisplay;
extern IMGNODE overlay_fbcopy;
extern IMGNODE overlay_fbdisplay;
extern IMGNODE flex_fbdisplay;
extern unsigned int pic_addr;

extern unsigned int GUI_LCM_XMAX,GUI_LCM_YMAX,LCD_CLK;
extern REGION G_REG_DIR;
extern REGION G_REG_FLR;
extern REGION G_REG_TIME;
extern REGION G_REG_DAY;
extern REGION G_REG_WEEK;
extern REGION G_REG_ALARM;
extern REGION G_REG_BKGND;
extern REGION G_REG_LOGO;
extern REGION G_REG_OTHER;
extern REGION G_REG_VIDEO;
extern REGION G_REG_TXT;
unsigned int BKGND_wait;
unsigned int BKGND_effect;

extern unsigned int G_LFTTXT_txt_vfmode;
extern unsigned int G_LFTTXT_vf_speed;
extern unsigned int G_LFTTXT_txt_color;

REGION G_REG_DIR_T2;
REGION G_REG_FLR_T2;
REGION G_REG_ALARM_T2;

REGION REG_DES;
//extern filestruct File_RAM[FOLDER_NUM][FILE_NUM_IN_FOLDER];

volatile unsigned int LIFT_FLAG;
volatile unsigned int Flag_CN;
_enum_DMODE G_DispMode = dmode_0C;

extern IMGNODE ptr;
REGION DisplayRegion[11];
Flr_Map flr_map[50];

flr flr_n;
char dir_num;
char state_num;

LIFT_WORK_INFO lift_work_info;

int LIFT_UPDATE=0;

char * pDir_fixbkg[4] =
{
	"/mnt/nand1-2/LIFT/LIFT_0C/BKGND/FLR_BSD/fixedbkgnd.bmp",
	"/mnt/nand1-2/LIFT/LIFT_90C/BKGND/FLR_BSD/fixedbkgnd.bmp",
	"/mnt/nand1-2/LIFT/LIFT_180C/BKGND/FLR_BSD/fixedbkgnd.bmp",
	"/mnt/nand1-2/LIFT/LIFT_270C/BKGND/FLR_BSD/fixedbkgnd.bmp",
};

#define MAXLINE 80
#define SERV_PORT 8000

int usbdisk_is_insert()
{
	FILE *p;
	char bInterfaceClassNum[10];
	
	if( access("/sys/devices/platform/w55fa95-ohci/usb1/1-1/1-1:1.0/bInterfaceClass", 0) == 0)
	{
		p = fopen("/sys/devices/platform/w55fa95-ohci/usb1/1-1/1-1:1.0/bInterfaceClass","r");
		if(p<=0)
		{
			printf("open bInterfaceClass failed\n");
			return 0;
		}

		memset(bInterfaceClassNum,0,10);
		fread(bInterfaceClassNum,10,1,p);
		fclose(p);
		
		if( (bInterfaceClassNum[0]=='0') && (bInterfaceClassNum[1]=='8') )
		{
			//printf("bInterfaceClass = %s\n",bInterfaceClassNum);
			return 1;
		}
	}
	
	
	if( access("/sys/devices/platform/w55fa95-ohci/usb1/1-2/1-2:1.0/bInterfaceClass", 0) == 0)
	{
		p = fopen("/sys/devices/platform/w55fa95-ohci/usb1/1-2/1-2:1.0/bInterfaceClass","r");
		if(p<=0)
		{
			printf("open bInterfaceClass failed\n");
			return 0;
		}

		memset(bInterfaceClassNum,0,10);
		fread(bInterfaceClassNum,10,1,p);
		fclose(p);
		
		if( (bInterfaceClassNum[0]=='0') && (bInterfaceClassNum[1]=='8') )
		{
			//printf("bInterfaceClass = %s\n",bInterfaceClassNum);
			return 1;
		}
	}
	return 0;						

}


int enable_backlight()
{
	int fb_fd;
	int brightness = 99;
	if ((fb_fd = open(FB_DEV, O_RDWR)) < 0) {
		printf("open device %s failed", FB_DEV);
		return -1;
	}
	ioctl(fb_fd, VIDEO_DISPLAY_ON);
	ioctl(fb_fd, IOCTL_LCD_BRIGHTNESS, &brightness);
	//sleep(1);
	close(fb_fd);
	return 0;
}


int machinetype_is_network()
{
	  FILE *fp;
	  char buf[PROCBUFSIZ];
	  char *name;

	  /* Open /proc/net/dev. */
	  fp = fopen (_PATH_PROC_NET_DEV, "r");
	  if (fp == NULL)
	  {   
		  printf("open proc file error\n");
		  return 0; 
	  }   

	  /* Drop header lines. */
	  fgets (buf, PROCBUFSIZ, fp);
	  fgets (buf, PROCBUFSIZ, fp);

	 
	  while (fgets (buf, PROCBUFSIZ, fp) != NULL)
	  {   
		 
		  if(strstr(buf,"eth0:")!=NULL)
		  {
		  	  fclose(fp);
		      return 1;
		  }
	  }   
	  fclose(fp);
	  return 0;

}



int get_mac(char * mac, int len_limit)    //返回值是实际写入char * mac的字符个数（不包括'\0'）
{
    struct ifreq ifreq;
    int sock;

    if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror ("socket");
        return -1;
    }
    strcpy (ifreq.ifr_name, "eth0");    //Currently, only get eth0

    if (ioctl (sock, SIOCGIFHWADDR, &ifreq) < 0)
    {
        perror("ioctl");
        return -1;
    }
    return snprintf (mac, len_limit, "%02X.%02X.%02X.%02X.%02X.%02X",\
	 (unsigned char) ifreq.ifr_hwaddr.sa_data[0], (unsigned char) ifreq.ifr_hwaddr.sa_data[1],\
	 (unsigned char) ifreq.ifr_hwaddr.sa_data[2], (unsigned char) ifreq.ifr_hwaddr.sa_data[3],\
	 (unsigned char) ifreq.ifr_hwaddr.sa_data[4], (unsigned char) ifreq.ifr_hwaddr.sa_data[5]);
}


int main()
{	
	int i;
	int num = 0;
	int cc;
	
	char print_bf[100];
	
	FILE *fp=NULL;
	
	G_DispMode = GetSysCfg();
	printf("\n\n%d\n\n",G_DispMode);
	if((G_DispMode == dmode_90C) || (G_DispMode == dmode_270C))
	{
		i = GUI_LCM_XMAX;
		GUI_LCM_XMAX = GUI_LCM_YMAX;
		GUI_LCM_YMAX = i;
	}
	
	if(G_DispMode == dmode_error)
	{
		G_DispMode = dmode_0C;
		LCD_CLK = 1;
		GUI_LCM_XMAX = 800;
		GUI_LCM_YMAX = 600;
	}	

	v4a_initial();
	v4a_initscreen(GUI_LCM_XMAX,GUI_LCM_YMAX);
	v4a_enablescreen(1);
	v4a_displaybkgnd(1);
	
	v4a_drawrect(&bkgnd_fbdisplay,gui_rect(0,0,GUI_LCM_XMAX,GUI_LCM_YMAX),ARGB(0,0,0,0));
	Display_Print_Init();
	Display_Print("Boot Vision: 4A01_boot_1.0");
	enable_backlight();	
	
	if( 1==machinetype_is_network() )
	{
		Display_Print("Machine Type: Network");
		
		char    buffer[18];
		int     nRtn ;
		
		nRtn = get_mac(buffer, sizeof(buffer));
		if(nRtn > 0)
		{
			fp=fopen("/mnt/nand1-2/mac","w");
				fwrite(buffer,strlen(buffer),1,fp);
			fclose(fp);
		}		
			
		memset(print_bf,0,100);
		strcat(print_bf,"Terminal MAC: ");
		strcat(print_bf,buffer);

		Display_Print(print_bf);
		
		
		if( access("/mnt/nand1-2/terminal_ip", 0) == 0 )
		{
			memset(buffer,0,18);
			fp=fopen("/mnt/nand1-2/terminal_ip","r");
				fread(buffer,18,1,fp);
			fclose(fp);
			
			memset(print_bf,0,100);
			strcat(print_bf,"Terminal Static IP: ");
			strcat(print_bf,buffer);

			Display_Print(print_bf);
		}
		
		else
		{	
			fp=fopen("/mnt/nand1-2/terminal_ip","w");
				fwrite("192.168.2.188",strlen("192.168.2.188"),1,fp);
			fclose(fp);
			Display_Print("Terminal Static IP: 192.168.2.188");		
		}
		
		fp=fopen("/mnt/nand1-2/server_ip","r");
		if(fp!=NULL)
		{
			memset(buffer,0,18);
			fread(buffer,18,1,fp);
			fclose(fp);
			
			memset(print_bf,0,100);
			strcat(print_bf,"Server IP: ");
			strcat(print_bf,buffer);

			Display_Print(print_bf);
    	}
    	else
    	{
    		fp=fopen("/mnt/nand1-2/server_ip","w");
			fwrite("192.168.2.100",strlen("192.168.2.100"),1,fp);
			fclose(fp);		
			Display_Print("Server IP: 192.168.2.100");   	
    	}		
			
	}
	else
		Display_Print("Machine Type: Non-network");
	
	sleep(6);

	system("mount -t ext3 /dev/sdb1 /mnt/sdcard");
	system("mount -t vfat /dev/sdb1 /mnt/sdcard");
	system("mount -t vfat /dev/sdc1 /mnt/sdcard");
	
	if( access("/mnt/sdcard/LIFTUPDATE/LIFT", 0) == 0 )
	{	
		system("mv /mnt/sdcard/LIFTUPDATE/LIFT /mnt/sdcard/");
		LIFT_UPDATE = 1;			
	}
	
	if( access("/mnt/sdcard/LIFT", 0) == 0 )
	{	
		Display_Print("Find LIFT in USB Disk");
		ProcessSDStatus();
		if(LIFT_UPDATE)
		{
			system("rm -rf /mnt/sdcard/LIFTUPDATE/LIFT");
			system("rm -rf /mnt/sdcard/LIFT");
			return 0;
		}
		while(cc=usbdisk_is_insert());								
	}
	else
	{
		if( access("/mnt/nand1-2/firmware.bin", 0) == 0 )
		{
			Display_Print("No LIFT for Updating, Jump to Init System");
			sleep(2);
			v4a_displaybkgnd(0);
			v4a_displayoverlay(0);
			return 0;
		}
		else
		{
			Display_Print("No Firmware, Please Insert Fat32 USB Disk");
			while(1)
			{		
				if( cc=usbdisk_is_insert() )
				{
					sleep(8);
					system("mount -t vfat /dev/sdb1 /mnt/sdcard");
					system("mount -t vfat /dev/sdc1 /mnt/sdcard");
					if( access("/mnt/sdcard/LIFT", 0) == 0 )
					{	
						Display_Print("Find LIFT in USB Disk");
						ProcessSDStatus();
						if(LIFT_UPDATE)
						{
							return 0;
						}
						while(cc=usbdisk_is_insert());
						v4a_displaybkgnd(0);
						v4a_displayoverlay(0);
						return 0;							
					}
					else
					{
						sleep(1);
						continue;	
					}	
				}
					
				
				sleep(1);	
			
			}
		}
	}
	v4a_displaybkgnd(0);
	v4a_displayoverlay(0);
	return 0;
}	

